package com.example.demo.practice;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.demo.practice.innerclass.DownApkServer;
import com.example.demo.practice.tool.ServerHttp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class Setting extends Activity {
    private String user = "";
    ListView listView;
    private ServerHttp serverHttp;
    private List<info> mListInfo = new ArrayList();

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            JSONArray jsonArray=serverHttp.getData();
            String versionName = "";
            try {
                // ---get the package info---
                PackageManager pm = Setting.this.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(Setting.this.getPackageName(), 0);
                versionName = pi.versionName;

                if (versionName == null || versionName.length() <= 0) {
                    return ;
                }
            } catch (Exception e) {
                Log.e("VersionInfo", "Exception", e);
            }
            JSONObject jsonObject;
            try {
                jsonObject=jsonArray.getJSONObject(0);
                String name=jsonObject.getString("name");
                if(!name.equals(versionName)){
                    new AlertDialog.Builder(Setting.this)
                            .setTitle("版本更新")
                            .setMessage("发现新的版本，点击确定开始下载，下载完成后自动安装")
                            .setNegativeButton("取消",null)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    update();
                                }
                            })
                            .show();
                }
                else {
                    new AlertDialog.Builder(Setting.this)
                            .setTitle("版本更新")
                            .setMessage("已是最新版本")
                            .setPositiveButton("关闭",null)
                            .show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            serverHttp.clear();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);

        listView = findViewById(R.id.menu);
        setInfo();  //给信息赋值函数，用来测试
        listView.setAdapter(new ListViewAdapter(mListInfo));
        //处理Item的点击事件
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        serverHttp=new ServerHttp(handler);
                        serverHttp.setUrl("Version");
                        break;
                    default:
                        break;

                }
            }
        });

        Button button1 = findViewById(R.id.picture);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView username = findViewById(R.id.username);
                String display = username.getText().toString().trim();
                if (display.equals("点击")) {
                } else {
                    Intent intent = new Intent(Setting.this, UserCenter.class);
                    intent.putExtra("user", user);
                    startActivityForResult(intent, 2);
                }
            }
        });
    }

    private void update() {
        Context ctx = Setting.this;
        String url="http://192.168.1.165:8081/DownLoadAPK";
        if (canDownloadState(ctx)) {
            Log.e("UpdateVersion", "DownloadManager 可用");
            Intent downloadApkIntent = new Intent(ctx, DownApkServer.class);
            Bundle bundle = new Bundle();
            bundle.putString("downloadUrl", url);
            bundle.putString("title", "app-release");
            downloadApkIntent.putExtra("download", bundle);
            ctx.startService(downloadApkIntent);
        } else {
            Log.e("UpdateVersion", "DownloadManager 不可用");
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(url);
            intent.setData(content_url);
            ctx.startActivity(intent);
        }

    }

    private static boolean canDownloadState(Context ctx) {
        try {
            int state = ctx.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case 1:
                user = data.getStringExtra("user");
                TextView username = findViewById(R.id.username);
                username.setText(user);
                break;
            case 2:
                user = data.getStringExtra("user");
                if (user.equals("")) {
                    TextView username1 = findViewById(R.id.username);
                    username1.setText("点击头像登陆");
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }


    public class ListViewAdapter extends BaseAdapter {
        View[] itemViews;

        public ListViewAdapter(List<info> mlistInfo) {
            // TODO Auto-generated constructor stub
            itemViews = new View[mlistInfo.size()];
            for (int i = 0; i < mlistInfo.size(); i++) {
                info getInfo = mlistInfo.get(i);    //获取第i个对象
                //调用makeItemView，实例化一个Item
                itemViews[i] = makeItemView(
                        getInfo.getTitle(), getInfo.getAvatar()
                );
            }
        }

        public int getCount() {
            return itemViews.length;
        }

        public View getItem(int position) {
            return itemViews[position];
        }

        public long getItemId(int position) {
            return position;
        }

        //绘制Item的函数
        private View makeItemView(String strTitle, int resId) {
            LayoutInflater inflater = (LayoutInflater)
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 使用View的对象itemView与R.layout.item关联
            View itemView = inflater.inflate(R.layout.my_item, null);

            // 通过findViewById()方法实例R.layout.item内各组件
            TextView title = itemView.findViewById(R.id.title);
            title.setText(strTitle);    //填入相应的值
            ImageView image = itemView.findViewById(R.id.img);
            image.setImageResource(resId);

            return itemView;
        }


        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                return itemViews[position];
            return convertView;
        }
    }

    public void setInfo() {
        mListInfo.clear();
        int i = 0;
        ArrayList<String> item = new ArrayList();
        item.add("关于我们");
        item.add("检查更新");
        int items[] = new int[2];
        items[0] = R.drawable.my_item2;
        items[1] = R.drawable.my_item3;
        while (i < 2) {
            info information = new info();
            information.setId("menu" + i);
            information.setTitle(item.get(i));
            information.setAvatar(items[i]);

            mListInfo.add(information); //将新的info对象加入到信息列表中
            i++;
        }
    }


}